package log

import (
	"fmt"
	"github.com/op/go-logging"
	"os"
	"path"
	p "xrt/utils/file/path"
)

var log = logging.MustGetLogger("xrt")

var format = logging.MustStringFormatter(
	`%{color}%{time:2006-01-02 15:04:05.000} %{module}] > %{id}|%{level:.5s}]%{color:reset} %{message}`,
)

func NewLogger(pathName string, level string) {
	if dirExist, _ := p.Exists(path.Dir(pathName)); !dirExist {
		os.MkdirAll(path.Dir(pathName), 0777)
	}
	os.Create(pathName)
	logFile, err := os.OpenFile(pathName, os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println(err)
	}
	lLevel, _ := logging.LogLevel(level)

	fileLog := logging.NewLogBackend(logFile, "", 0)
	fileFormatter := logging.NewBackendFormatter(fileLog, format)
	fileLeveled := logging.AddModuleLevel(fileFormatter)
	fileLeveled.SetLevel(lLevel, "")

	stdLog := logging.NewLogBackend(os.Stderr, "", 0)
	stdFormatter := logging.NewBackendFormatter(stdLog, format)
	stdLeveled := logging.AddModuleLevel(stdFormatter)
	stdLeveled.SetLevel(lLevel, "")
	logging.SetBackend(fileLeveled, stdLeveled)
}

var Info = log.Info
var Infof = log.Infof
var Notice = log.Notice
var Noticef = log.Noticef
var Debug = log.Debug
var Debugf = log.Debugf
var Warning = log.Warning
var Warningf = log.Warningf
var Error = log.Error
var Errorf = log.Errorf
var Critical = log.Critical
var Criticalf = log.Criticalf

func CheckError(err error) {
	if err != nil {
		Errorf("Fatal error: %s", err.Error())
	}
}
